//
// @author				mitchell
// @description		020101.html页面的JS打包文件 注意引用顺序
// @lastmodified		$2010-7 - 15$
$(document).ready(function(){
	// res_url
	if (js_context && js_context.res_url) {
		js_context.res_url = function() {
			var res_url = js_context.res_url;
			var func = function(path) {
				var url = res_url;
				path = !path ? "" : path.replace(/(.+?)\.(js|css|jpg|gif|png|cur)$/i, "$1"+(js_context.jsrevision || "")+".$2");
				return url + path;
			};
			func.toString = function() {
				return res_url;
			};
			func.get = func;
			return func;
		}();
	}
	
	var current_cache = 1;
	var total_cache = 1;
	var map;
	var marker_arr = js_context.marker;
	var markers = {};
	var marker_cache = '';
	var marker_cacheid = '';
	var OLatlngs = [];
	
	//store cache.
	var store_cache = {};
	//user latlng.
	var position_marker = false;
	//icon_cache
	var icon_cache = false;
	//instance create map...
	if(js_context.c_lat !== undefined && js_context.c_lng !== undefined){
		creat_map(js_context.c_lat,js_context.c_lng);
	}else{
		creat_map(39.904214,116.407413);
	}

	function owner_position(){
		var localSpaceX;
		var localSpaceY;
		//IE filter
		var geo = navigator.geolocation;
		if(!geo && google && google.gears) {
			geo = google.gears.factory.create('beta.geolocation');
		}
		if (geo) {
			geo.getCurrentPosition(GeoDecode);
		}else{
			alert('无法获取您当前位置，您可以在地图上选取您所在的');
		}
	}
	
	function GeoDecode(position) {
		localSpaceX = position.latitude || position.coords.latitude;
		localSpaceY = position.longitude || position.coords.longitude;
		latlng = new google.maps.LatLng(localSpaceX,localSpaceY);
		//map = creat_map(localSpaceX,localSpaceY);
		map.setZoom(14);
		map.setCenter(latlng);
		var marker = new google.maps.Marker({});
		marker.setMap();
		position_marker = new google.maps.Marker({
			//icon: js_context.res_url('images/shangjia.gif'),
			map: map,
			draggable: true,
		    position: latlng
		});
	
//		$("#onLand").attr('lat',localSpaceX);
//		$("#onLand").attr('lng',localSpaceY);
		google.maps.event.addListener(position_marker, 'drag', function() {
			$("#marker_address").val('加载中...');
			$("#latlnginfo").html(position_marker.getPosition().lat()+','+position_marker.getPosition().lng());
			$("#latlnginfo").attr('lat',position_marker.getPosition().lat());
			$("#latlnginfo").attr('lng',position_marker.getPosition().lng());
		});
			  
		google.maps.event.addListener(position_marker, 'dragend', function() {
			geocodePosition(position_marker.getPosition());
			getround(position_marker.getPosition().lat(),position_marker.getPosition().lng(),1)
		});
	}
	
	function creat_map(latitude,longitude){
		latlng = new google.maps.LatLng(latitude,longitude);
		var myOptions = {
			    zoom: 11,
			    center: latlng,
			    mapTypeId: 'roadmap',
			    mapTypeControl:false,
			    streetViewControl:false,
			    navigationControl:true,
			    navigationControlOptions: {
			        style: google.maps.NavigationControlStyle.ZOOM_PAN,
			        position: google.maps.ControlPosition.TOP_LEFT
			    },
			    scaleControl: true 
		};
		map = new google.maps.Map(document.getElementById("search_map"), myOptions);
		return map;
	}
	
	//from positon get address
	function geocodePosition(pos) {
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({
			latLng: pos
		}, function(responses) {
			if (responses && responses.length > 0) {
				var result_address = responses[0].formatted_address.split(" 邮政编码");
				$("#marker_address").val(result_address[0]);
				input_address = $("#marker_address").attr("input_address",'');
				$("#marker_address").css('background-color','#cccccc').attr('readonly','true');
			} else {
				$("#marker_address").val('获取不到相对应的地址~.');
			}
		});
	}
	
	
	
	google.maps.event.addListener(map, 'click', function(event) {
		if(position_marker) position_marker.setVisible(false);
		
		placeMarker(event.latLng);
		google.maps.event.addListener(position_marker, 'drag', function() {
			$("#marker_address").val('加载中...');
			$("#latlnginfo").html(position_marker.getPosition().lat()+','+position_marker.getPosition().lng());
			$("#latlnginfo").attr('lat',position_marker.getPosition().lat());
			$("#latlnginfo").attr('lng',position_marker.getPosition().lng());
			
		});
			  
		google.maps.event.addListener(position_marker, 'dragend', function() {
			geocodePosition(position_marker.getPosition());
			getround(position_marker.getPosition().lat(),position_marker.getPosition().lng(),1)
		});
		getround(position_marker.getPosition().lat(),position_marker.getPosition().lng(),1)
	});
	
	if(js_context.user_lat && js_context.user_lng){
		user_latlng = new google.maps.LatLng(js_context.user_lat,js_context.user_lng);
		position_marker = new google.maps.Marker({
			//icon: js_context.res_url('images/shangjia.gif'),
			map: map,
			draggable: true,
		    position: user_latlng
		});
		map.setZoom(14);
		map.setCenter(user_latlng);
		google.maps.event.addListener(position_marker, 'drag', function() {
			$("#marker_address").val('加载中...');
			$("#latlnginfo").html(position_marker.getPosition().lat()+','+position_marker.getPosition().lng());
			$("#latlnginfo").attr('lat',position_marker.getPosition().lat());
			$("#latlnginfo").attr('lng',position_marker.getPosition().lng());
		});
			  
		google.maps.event.addListener(position_marker, 'dragend', function() {
			geocodePosition(position_marker.getPosition());
			getround(position_marker.getPosition().lat(),position_marker.getPosition().lng(),1)
		});
	}else{
		owner_position();
	}
	
	if(marker_arr != undefined && marker_arr.length>0){
		var marker_cache_info = [];
		for(var i=0;i<marker_arr.length;i++){
			
			makeMarker(marker_arr[i].lat,marker_arr[i].lng,marker_arr[i].name,marker_arr[i].sid,i+1);
			marker_cache_info[i] = marker_arr[i];
			if(marker_arr.length > 10 && i == 9){
				//set store cache
				store_cache[current_cache] = marker_cache_info;
				break;
			}
		}
		var LatLngBounds = new google.maps.LatLngBounds();
		for (var i in OLatlngs){
			LatLngBounds.extend(OLatlngs[i]);
		}
				marker_arr;
		icon_cache = {'lat':position_marker.getPosition().lat(),'lng':position_marker.getPosition().lng()};
		
		map.fitBounds( LatLngBounds );
		if(map.getZoom()>14)map.setZoom(14);
		map.setCenter();
		bind_click();
	}
	
	function placeMarker(location) {
		position_marker = new google.maps.Marker({
			position: location,
			draggable: true,
			map: map
		});
		$("#latlnginfo").html(position_marker.getPosition().lat()+','+position_marker.getPosition().lng());
		$("#latlnginfo").attr('lat',position_marker.getPosition().lat());
		$("#latlnginfo").attr('lng',position_marker.getPosition().lng());
		
		geocodePosition(position_marker.getPosition());
		return position_marker;
	}
	
	function makeMarker(latitude,longitude,title,cacheid,tagicon){
		var OLatlng = new google.maps.LatLng(latitude,longitude);
		tagicon = (tagicon=='')?'loc':tagicon;
		var img = js_context.res_url('images/marker/t'+tagicon+'.gif');
		var marker = new google.maps.Marker({map: map, position: OLatlng,title:title, icon: img });
		OLatlngs[cacheid] = OLatlng;
		marker.cacheid = cacheid;
		marker.tagicon = tagicon;
		markers[cacheid] = marker;
		google.maps.event.addListener(marker, 'click', function(LatLng) {
			show_storeinfo(cacheid,title,tagicon);
			$(".store_"+cacheid).removeClass("seek-fruit");
			$(".store_"+cacheid).addClass("seek-fruit1");
			$('.seek-fruit1').not(".store_"+cacheid).addClass('seek-fruit').removeClass("seek-fruit1");
		});
		google.maps.event.addListener(marker, 'mouseout', function(){
			if(marker_cacheid != tagicon){
				marker.setIcon(js_context.res_url('images/marker/t'+tagicon+'.gif'));
				$(".store_"+cacheid).removeClass("seek-fruit1");
				$(".store_"+cacheid).addClass("seek-fruit");
			}
		});
		google.maps.event.addListener(marker, 'mouseover', function(){
			if(marker_cacheid != tagicon){
				marker.setIcon(js_context.res_url('images/marker/h'+tagicon+'.gif'));
				$(".store_"+cacheid).removeClass("seek-fruit");
				$(".store_"+cacheid).addClass("seek-fruit1");
			}
		});
	}
	
	function show_storeinfo(sid,title,tagicon){
		if(marker_cache != ''){
			if(tagicon == marker_cacheid){
				return false;
			}
			marker_cache.setIcon(js_context.res_url('images/marker/t'+marker_cacheid+'.gif'));
			marker_cache.setZIndex(10);
		}
		marker_cache = markers[sid];
		marker_cacheid = tagicon;
		marker_cache.setZIndex(10000);
		marker_cache.setIcon(js_context.res_url('images/marker/h'+marker_cacheid+'.gif'));
		
		var mapBrounds = map.getBounds();
		var maxX = map.getBounds().getNorthEast().lng();   
		var maxY = map.getBounds().getNorthEast().lat();   
		var minX = map.getBounds().getSouthWest().lng();   
		var minY = map.getBounds().getSouthWest().lat();   
			
		var in_X = marker_cache.getPosition().lng();
		var in_Y = marker_cache.getPosition().lat();
		if(in_X < minX || in_X > maxX || in_Y < minY || in_Y > maxY){
			map.panTo(marker_cache.getPosition());
		}
		
	}
	
	function clear_markers(m){
		OMarkerStatus = null;
		for (var i in m){
			m[i].setMap(null);
		}
	}
	


	//insert userinfo
	$("#position_tj").click(function(event){
		event.preventDefault();
		var address = $("#marker_address").val();
		var lat = $("#latlnginfo").attr('lat');
		var lng = $("#latlnginfo").attr('lng');
		if(address==""){
			alert("请先确定您的位置！");
			return false;
		}
		if(!lat){
			alert("请先确定您的位置！");
			return false;
		}
		var url = $(this).attr("form_url");
		$(".position_loading").show();
		$.get(url, {'address' : address , 'lat' : lat , 'lng' : lng},function(result){
			$(".position_loading").hide();
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			if(!data){
				alert('提交失败');
				return false;
			}
			if(data == 'notlogin'){
				self.location = js_context.base_url+'login?r='+document.URL;
				return false;
			}
			if(data == 'error'){
				alert("请先登录！");
				return false;
			}
			self.location = js_context.base_url+'search/map';
		},"json")
	});
	
	function bind_click(){
		$('.seek-fruit').click(function(event){
			event.preventDefault;
			$(this).attr('class','seek-fruit1');
			$('.seek-fruit1').not(this).attr('class','seek-fruit');
			show_storeinfo($(this).attr('sid'), $(this).attr('store'), $(this).attr('tagicon'));
		});

	}
	$('#next_page').click(function(event){
		event.preventDefault;
		var page = $(this).attr('page');
		if((page == current_cache) || page <= 1) return false;
		
		getround(position_marker.getPosition().lat(),position_marker.getPosition().lng(),page);
	});
	$('#previous_page').click(function(event){
		event.preventDefault;
		var page = $(this).attr('page');
		if(page < 1) return false;
		getround(position_marker.getPosition().lat(),position_marker.getPosition().lng(),page);
	});
	function getLatLng(address){
		var geocoder = new google.maps.Geocoder();  
		if (geocoder) {  
			geocoder.geocode({'address':'北京 '+address,'region':'cn'}, function(results, status) {  
			    if (status == google.maps.GeocoderStatus.OK) {  
			         if (results[0]) {  
			        	 // alert(results[0].formatted_address);  
			             address = results[0].formatted_address;
			             latlng = results[0].geometry.location;
			             $("#latlnginfo").html(latlng.lat()+","+latlng.lng());
			             $("#latlnginfo").attr("lat",latlng.lat());
			             $("#latlnginfo").attr("lng",latlng.lng());
			         }  
			    } else {
			        alert("Geocoder failed due to: " + status);  
			    }  
			});  
		}
	}
	//getLatLng('大半截胡同');
	  
	function getround(lat,lng,page){
		loaddiv(true);
		var store_cache_mir = getStoreCache(lat,lng,page);
		
		if(store_cache_mir == 0){
			var url = js_context.base_url+'ajax/search/s_store';
			$.get(url, {'page' : page , 'lat' : lat , 'lng' : lng},function(result){
				$(".position_loading").hide();
				if(result.success == false){
					alert('通讯失败');
					return false;
				}
				if(result.message == false){
					alert('您选择地点附近没有餐厅，请重新选取位置');
					return false;
				}
				
				//SHOW VIEW INFO..
				$("#search_num").html(result.message.length);
				$("#search_distance").html(result.distance);
				$(".search_view_info").show();
				
				var data = result.message;
				if(!data){
					alert('提交失败');
					return false;
				}
				//set store cache...
				
				marker_arr = data;
				var data = getStore(page);
				var total_page = Math.ceil(marker_arr.length/10);
				
				var current_page = page;
				var html = '';
				for(var i=0;i<data.length;i++){
					var iconnum = i+1;
					html += '<div class="seek-fruit" store="'+data[i].name+'" tagicon="'+iconnum+'" sid="'+data[i].sid+'">';
					html += '<h3><span>'+iconnum+'.<a href="'+js_context.base_url+'store/'+data[i].sid+'">'+data[i].name+'</a> <b>-'+data[i].distance+'米</b></span>';
					html += '<font><div class="score-1"></div></font></h3><div style="clear:both;"></div><p>'+data[i].address+'</p></div>';
				}
				$("#seek_results").html(html);
				// page..
				var previous_page = $('#previous_page');
				var next_page = $('#next_page');
				
				if(total_page == 1){$("#page").hide();}
				else{
					if(current_page == 1){
						previous_page.hide();
					}else{
						previous_page.attr('page',parseInt(current_page)-1).show();
					}
	
					if(current_page >= total_page){
						next_page.hide();
					}else{
						next_page.attr('page',parseInt(current_page)+1).show();
					}
					$("#page").show();
				}
				setStoreCache(lat,lng,current_page,data);
				current_cache = current_page;
				total_cache = total_page;

				
				//clear cache
				clear_markers(markers);
				OLatlngs = [];
				for(var i=0;i<data.length;i++){
					var iconnum = i+1;
					makeMarker(data[i].lat,data[i].lng,data[i].name,data[i].sid,iconnum);
				}
				//bind map
				setBounds(OLatlngs);
				bind_click();
				loaddiv(false);
			},"json")
		}
		else if(store_cache_mir == 'page'){
			var data = getStore(page);
			var current_page = page;
			var total_page = Math.ceil(marker_arr.length/10);

			var html = '';
			for(var i=0;i<data.length;i++){
				var iconnum = i+1;
				html += '<div class="seek-fruit" store="'+data[i].name+'" tagicon="'+iconnum+'" sid="'+data[i].sid+'">';
				html += '<h3><span>'+iconnum+'.<a href="'+js_context.base_url+'store/'+data[i].sid+'">'+data[i].name+'</a> <b>-'+data[i].distance+'米</b></span>';
				html += '<font><div class="score-1"></div></font></h3><div style="clear:both;"></div><p>'+data[i].address+'</p></div>';
			}
			$("#seek_results").html(html);

			// page..
			var previous_page = $('#previous_page');
			var next_page = $('#next_page');
			
			if(total_page == 1){$("#page").hide();}
			else{
				if(current_page == 1){
					previous_page.hide();
				}else{
					previous_page.attr('page',parseInt(current_page)-1).show();
				}

				if(current_page >= total_page){
					next_page.hide();
				}else{
					next_page.attr('page',parseInt(current_page)+1).show();
				}
				$("#page").show();
			}
			setStoreCache(lat,lng,current_page,data);
			current_cache = current_page;
			total_cache = total_page;

			
			//clear cache
			clear_markers(markers);
			OLatlngs = [];
			for(var i=0;i<data.length;i++){
				var iconnum = i+1;
				makeMarker(data[i].lat,data[i].lng,data[i].name,data[i].sid,iconnum);
			}
			//bind map
			setBounds(OLatlngs);
			bind_click();
			loaddiv(false);
		}else{
			viewStoreCache(store_cache_mir,total_cache,page);
		}
	}
	
	function getStore(page){
		var data = new Array();
		var start = false;
		var j = 0;
		for(var i=0;i<marker_arr.length;i++){
			if((page-1)*10 == i){
				var start = true;
			}
			
			if(start){
				data[j] = marker_arr[i];
				j++;
			}
			
			if(page*10 == (i+1)){
				break;
			}
		}
		return data;
	}
	
	function setBounds(m){
		var LatLngBounds = new google.maps.LatLngBounds();
		for(var i in m){
			LatLngBounds.extend(m[i]);
		}
		var lng = LatLngBounds.getCenter().lng()-(LatLngBounds.getSouthWest().lng() - LatLngBounds.getNorthEast().lng())*(360/950);
		var center = new google.maps.LatLng(LatLngBounds.getCenter().lat(),lng);
		map.fitBounds( LatLngBounds )
		if(map.getZoom()>18)map.setZoom(18);
		map.panTo( center );
		
	}
    function loaddiv(view){
	    if(view){
		    $("#loading").show();
		    $("#page,#seek_results").hide();
	    }else{
		    $("#loading").hide();
		    $("#page,#seek_results").show();
	    }
    }
    
    function setStoreCache(lat,lng,page,store){
    	if(icon_cache && lat == icon_cache.lat && lng == icon_cache.lng){
    		if(store_cache != null && store_cache[page] != undefined){
        		return true;
    		}
    	}else{
    		store_cache = {};
    	}
		store_cache[page] = store;
		icon_cache = icon_cache = {'lat':position_marker.getPosition().lat(),'lng':position_marker.getPosition().lng()};;
    }
    
    function getStoreCache(lat,lng,page){
    	if(!icon_cache || lat != icon_cache.lat || lng != icon_cache.lng) return 0;

    	if(store_cache != null && store_cache[page] != undefined){
    		return store_cache[page];
    	}else{
    		return 'page';
    	}
    }
    
    function viewStoreCache(store,total,current){

    	var data = store;
    	var html = '';
		for(var i=0;i<data.length;i++){
			var iconnum = i+1;
			html += '<div class="seek-fruit" store="'+data[i].name+'" tagicon="'+iconnum+'" sid="'+data[i].sid+'">';
			html += '<h3><span>'+iconnum+'.<a href="'+js_context.base_url+'store/64">'+data[i].name+'</a></span>';
			html += '<font><div class="score-1"></div></font></h3><div style="clear:both;"></div><p>'+data[i].address+'</p></div>';
		}
		$("#seek_results").html(html);
		// page..
		var previous_page = $('#previous_page');
		var next_page = $('#next_page');
		
		if(total == 1){$("#page").hide();}
		else{
			if(current == 1){
				previous_page.hide();
			}else{
				previous_page.attr('page',parseInt(current)-1).show();
			}

			if(current >= total){
				next_page.hide();
			}else{
				next_page.attr('page',parseInt(current)+1).show();
			}
			$("#page").show();
		}
		current_cache = current;
		total_cache = total;
		
		//clear cache
		clear_markers(markers);
		OLatlngs = [];
		for(var i=0;i<data.length;i++){
			var iconnum = i+1;
			makeMarker(data[i].lat,data[i].lng,data[i].name,data[i].sid,iconnum);
		}
		//bind map
		setBounds(OLatlngs);
		bind_click();
		loaddiv(false);
    }

});
